package com.tlkg.qa.redistest.self.newer;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.util.JedisClusterCRC16;

public class RedisUtil {

	private static JedisCluster jedisCluster;
	private static Integer timeout = 30 * 1000;
	private static Integer maxRedirections = 6;
	private static GenericObjectPoolConfig genericObjectPoolConfig;

	private RedisUtil() {
	}

	static {
		genericObjectPoolConfig = new GenericObjectPoolConfig();
		genericObjectPoolConfig.setMaxTotal(1500);
		genericObjectPoolConfig.setMinIdle(8);
		genericObjectPoolConfig.setMaxIdle(100);
		genericObjectPoolConfig.setMaxWaitMillis(60 * 1000);

		Set<HostAndPort> haps = new HashSet<HostAndPort>();
		haps.add(new HostAndPort("10.200.70.43", 6370));
//		haps.add(new HostAndPort("10.200.70.43", 6371));
		haps.add(new HostAndPort("10.200.70.62", 6370));
//		haps.add(new HostAndPort("10.200.70.62", 6371));
		haps.add(new HostAndPort("10.200.70.64", 6370));
//		haps.add(new HostAndPort("10.200.70.64", 6371));
		jedisCluster = new JedisCluster(haps, timeout, maxRedirections, genericObjectPoolConfig);
	}

	public static String set(String key, String value) {
		return jedisCluster.set(key, value);
	}

	public static String get(String key) {
		return jedisCluster.get(key);
	}

	public static TreeSet<String> keys(String pattern) {
		TreeSet<String> keys = new TreeSet<>();
		Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();
		for (String k : clusterNodes.keySet()) {
			JedisPool jp = clusterNodes.get(k);
			Jedis connection = jp.getResource();
			try {
				keys.addAll(connection.keys(pattern));
			} catch (Exception e) {
				System.err.println(e.getMessage());
			} finally {
				connection.close();// 用完一定要close这个链接！！！
			}
		}
		return keys;
	}

	public static int getSlot(String key) {
		// 这东西 可以直接看到key 的分片数，就能知道放哪个 节点
		return JedisClusterCRC16.getSlot(key);
	}

	public static void main(String[] args) {
		int slot = getSlot("test_100000");
		System.out.println(slot);
	}
}
